package com.dome.network1;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

//用多线程优化TCP
public class MyTcp implements Runnable {
    //设定随机生成的文件名
    UUID uuid;
    private Socket accept;

    public MyTcp(Socket accept) {
        this.accept=accept;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream("C:\\git-lx\\" + uuid + ".txt"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
                bos.flush();
            }
            System.out.println("==================");
            //给客户端发送回馈信息
            OutputStream os = accept.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("上传成功");
            bw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}